<?php
declare (strict_types=1);

namespace app\controller;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use app\BaseController;
use app\common\TencentIm;
use app\extend\alipayglobal\DefaultAlipayClient;
use app\extend\alipayglobal\model\Amount;
use app\extend\alipayglobal\model\Order;
use app\extend\alipayglobal\model\ProductCodeType;
use app\extend\alipayglobal\request\order\AlipayCreateOrderRequest;
use app\model\Activity;
use app\model\Forum;
use app\model\Friends;
use app\model\IndexClass;
use app\model\News;
use app\model\NewsIssuer;
use app\model\Question;
use app\model\Recruit;
use app\model\Room;
use app\model\SecGoods;
use app\model\Store;
use app\model\StoreAssess;
use app\model\Talent;
use app\model\Users;
use app\Request;
use app\tool\Http;
use think\db\exception\DbException;
use think\db\Query;
use think\facade\Log;
use think\response\Json;



class IndexController extends BaseController
{
	protected array $middleware = [
		'Login' => ['except' => ['index','class', 'test', 'search', 'hot_talent', 'tests', 'start']],
		'Location' => ['only' => ['index']],
	];
	
	public $postCharset = "UTF-8";
	private $fileCharset = "UTF-8";
	
	
	function test(Request $request)
	{
		
		dd(	News::connect('zn_mysql')->insert(['users_id'=>2222]));
		$TencentIm = TencentIm::getInstance();
		$users = Users::select();
		foreach ($users as $user){
			$ret = json_decode($TencentIm->account_import($user->id, $user->nickname, config('app.static_host') . $user->head_image));
			if ($ret->ErrorCode != 0) {
				writeJson(0, $ret->ErrorInfo);
			}
		}
		
		exit;
		$data = [
			'service' => 'mobile.securitypay.pay',
			'partner' => '2088741537328262',
			'_input_charset' => 'UTF-8',
			'notify_url' => $request->domain() . '/Callback/Notify',
			'out_trade_no' => '41265155215981234',
			'subject' => 'kids clothing',
			'payment_type' => '1',
			'seller_id' => 'hkkululu@163.com',
			'body' => 'Glitterleggings',
			'currency' => 'HKD',
			'forex_biz' => 'FP',
			'refer_url' => 'http://testmerchant.com',
			'total_fee' => 0.01,
			'product_code' => 'NEW_WAP_OVERSEAS_SELLER',
			'trade_information' => ['business_type' => '5', 'other_business_type' => '用户增值服务'],
		];
		
		ksort($data);
		$stringToBeSigned = "";
		foreach ($data as $k => $v) {
		
			$isarray = is_array($v);
			if ($isarray) {
				$stringToBeSigned .= $k . '=' . json_encode($v,JSON_UNESCAPED_UNICODE ) . '&';
			} else {
				$stringToBeSigned .= $k . '='  .$v. '&';
			}
		}
		$stringToBeSigned = substr($stringToBeSigned, 0, strlen($stringToBeSigned)-1);
		dump('pre-sign string');
		dump($stringToBeSigned);

		$private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .
			wordwrap("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfPiOPWTr/DSBeVbaC2UIVeIXVMkwNMcOu7QuGd1b8sXlhhs4dALUDycCJWEyeVRcBGXq2KtQ8BBNMFBMLADtYAVqq35CbM/qJPZSXx424rwRGwtMvXbrRINME2XHScQopnTDqSLAIqpMsClcJbrrpCOA+Hnvqa8Dpy9l3aOqkzSbT77WQIu7RMQR602OdZ6XkEe1eH5V4zBvyOFa4RHXDjQZJoL/G2jH2Cg91aAjYhhSquU5hh3rSioRnup2SnsVyxF+emJeh5qgoquHsjJz1O09wHNaYtkmvc/O3Ya/cQBUCs3PyGxLkr47aHJfz/3zEj/yopx+I5RTz+bd2nJVrAgMBAAECggEBAJaEa6RBWWxfAeto5RyFMtuMkiPUaOJH2YjscmplPwmWzv6KJyRu2Kp99slbdwBpuVbGuKCblwQrbfoJN368d1tV3FeK/epVlUhHtr5IVwLsGwSvfmJVHBI0DoGU7utVAaAX/nZUwl9Oq9GC7IXz7iP6ycqtkb8gnrXegu1FdBTUeMMKxAFhbP7M6NkCpbSKOs0M/FF3GBYEDzldNEggupdnRh52hxQ/ds05TTllh4XhRTu5+Gb6QyI/4zmU6JTTdyQftiM3N5ZIDQlwxN0KqfUvEmyx27nDY4Gs8TnKG/S1vtVHcwnCnxrAucpSLx04eR5iq6DMys3u1eKCK/BJZaECgYEA8yYfnaPelADqFYSdoy5ROBZ+hGnuBuj95lOcTQbELvgFIJ23AP5PUTOgJYReZJmy2jkjW4geKHcpJQDe5j+zYyKzOc5Dv9os76KC2efM292cpH+AmymaL5kc/gRAORUx/CdzVUll3ulgtml3Y/DZhxA1T7hHtG5VMnShbqFnUUkCgYEAp6i9bRiJwbC8uz8P5NIr/ucXcSBZWyF0k2hrsiArNR13B5wbcjgSW5pq7blicJTpri+yxv+FEVcce96a12Trx+k8PeDfdNBhdXhWcIRd3VfzzTNLEuT7/o89+nlZ2+IVbiZUuUfS5YWpMvcSWSrILCTtjrcPRZF1l/0iODWiJRMCgYBDlU0kW+/542ctI/dM7ArXNClmVKs8cHZiFstS/ZZ6F6YVMsEzHXyebWMOCoTSIYZ88XTKdEMtrDFbf6p1BS+vVm3Km3JpWRM0aE9Gkg927VokvuvYNPAOWticIkJXm3SRScXc5tHR67xd92Kf/Mn5qJ+o0OfdVu2HYLOeNG6rQQKBgBfwokvHqzP7FpfuI0jbMekN+mzu35OBrXG3AVnH+iN1d5+gjNK8avKllAsp44KL4Oo8aVy887VMKQcO/DExefFrvmxfhcjaUHBDpKQgYn7OpkNwxZGHHOx2a7UuSsR4/fJiisqCFP0tHsHmQbp1v2t+QmWUghu+73mqbY51Khf9AoGBAJMRTBLjQlUI9aGmGZjjqf7eJtYcuW/Bx94tqi+LZjqBTm1KzWwJwUPSrIgc9x4+NfMWPIdiSPHckhRWrSnppmBY8N3P5nw9ST5nWLcjq4bL5YWG41bG15riLFk1Bf4iI4WxuWaWYNHkhguV17KlaNnRIAuFHkvgeYKYzWiZIdcz", 64, "\n", true) .
			"\n-----END RSA PRIVATE KEY-----";
		dump('private_key');
		dump($private_key);
		openssl_sign($stringToBeSigned, $sign, $private_key, OPENSSL_ALGO_SHA256);
		$sign = base64_encode($sign);
		
		$stringToBeSigned .= '&sign'.'='.$sign.'&'.'sign_type'.'='. 'RSA2';
		
		dump('sign');
		dump($sign);
		$url = 'https://intlmapi.alipay.com/gateway.do?';
		dump('result');
		dd($url.$stringToBeSigned);
		
	}
	
	/**
	 * 首页
	 * @return Json
	 */
	public function index(Request $request)
	{
		Log::record('首页');
		$lat = self::$latitude;
		$lng = self::$longitude;
		$pi = pi();
		$radius = 6371000;
		$store_list = Store::field("*,ACOS(SIN(($lat* $pi) / 180) * SIN((latitude * $pi) / 180 ) + COS(($lat* $pi) / 180 ) * COS((latitude * $pi) / 180 ) *COS(($lng* $pi) / 180 - (longitude * $pi) / 180 ) ) * $radius as distance")
			->order(['hot' => 'desc'])
			->where('status', 1)
			->limit(15)
			->select();
		$news_list = News::with(['issuer'])
			->order(['browse' => 'desc'])
			->limit(5)
			->select();
		$forum_list = Forum::with([
				'users',
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'forum']);
				}]
		)
			->order('browse', 'desc')
			->limit(5)
			->select();
//        $talent_list = Talent::with(['users'])
////            ->where('is_good',1)
//            ->order('id', 'desc')
//            ->limit(5)
//            ->select();
		$arr['hot_store'] = $store_list;
		$arr['hot_news'] = $news_list;
		$arr['hot_forum'] = $forum_list;
//        $arr['hot_talent'] = $talent_list;
		writeJson($arr);
	}
	
	function class()
	{
		$rows = IndexClass::where(['status'=>1])->order(['weigh'=>'desc'])->select();
		writeJson($rows);
	}
	
	/**
	 * 热门人才
	 * @return void
	 */
	function hot_talent()
	{
		$rows = Talent::with(['users'])
//            ->where('is_good',1)
			->orderRaw('rand()')
			->limit(100)
			->select();
		writeJson($rows);
	}
	
	/**
	 * 搜索
	 * @param string $keyword
	 * @return Json
	 * @throws DbException
	 */
	function search(string $keyword)
	{
		if (empty($keyword)) {
			writeJson(0, '无效关键词');
		}
		$list['Question']['count'] = Question::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Room']['count'] = Room::whereLike('room_name', '%' . $keyword . '%')->count();
		$list['Room']['types'] = [
			['type' => 1, 'name' => '出租', 'count' => Room::where(['type' => 1])->whereLike('room_name', '%' . $keyword . '%')->count()],
			['type' => 2, 'name' => '求租', 'count' => Room::where(['type' => 2])->whereLike('room_name', '%' . $keyword . '%')->count()],
			['type' => 3, 'name' => '出售', 'count' => Room::where(['type' => 3])->whereLike('room_name', '%' . $keyword . '%')->count()],
		];
		$list['News']['count'] = News::whereLike('title_s|content_s', '%' . $keyword . '%')->whereTime('createtime', '-7 days')->count();
		$list['SecGoods']['count'] = SecGoods::whereLike('content', '%' . $keyword . '%')->count();
		$list['Store']['count'] = Store::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['StoreAssess']['count'] = StoreAssess::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Forum']['count'] = Forum::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Activity']['count'] = Activity::whereLike('title', '%' . $keyword . '%')->count();
		$list['Activity']['types'] = [
			['type' => 1, 'name' => '线上活动', 'count' => Activity::where(['type' => 1])->whereLike('title', '%' . $keyword . '%')->count()],
			['type' => 2, 'name' => '线下活动', 'count' => Activity::where(['type' => 2])->whereLike('title', '%' . $keyword . '%')->count()],
		];
		$list['Recruit']['count'] = Recruit::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Recruit']['types'] = [
			['type' => 0, 'name' => '招聘', 'count' => Recruit::where(['type' => 0])->whereLike('title|content', '%' . $keyword . '%')->count()],
			['type' => 1, 'name' => '求职', 'count' => Recruit::where(['type' => 1])->whereLike('title|content', '%' . $keyword . '%')->count()],
		];
		$list['Talent']['count'] = Talent::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Talent']['types'] = [
			['type' => 1, 'name' => '优才计划', 'count' => Talent::where(['type' => 1])->whereLike('title|content', '%' . $keyword . '%')->count()],
			['type' => 2, 'name' => '高才计划', 'count' => Talent::where(['type' => 2])->whereLike('title|content', '%' . $keyword . '%')->count()],
			['type' => 3, 'name' => '专才计划', 'count' => Talent::where(['type' => 3])->whereLike('title|content', '%' . $keyword . '%')->count()],
			['type' => 4, 'name' => '留学', 'count' => Talent::where(['type' => 4])->whereLike('title|content', '%' . $keyword . '%')->count()],
		];
		$list['Friends']['count'] = Friends::whereLike('title|content', '%' . $keyword . '%')->count();
		$list['Friends']['types'] = [
			['type' => 1, 'name' => '交友', 'count' => Friends::where(['type' => 1])->whereLike('title|content', '%' . $keyword . '%')->count()],
			['type' => 2, 'name' => '活动', 'count' => Friends::where(['type' => 2])->whereLike('title|content', '%' . $keyword . '%')->count()],
		];
		writeJson($list);
	}
	
	/**
	 * ip判断
	 * @param Request $request
	 * @return void
	 */
	function start(Request $request)
	{
		$ret = Http::get('https://restapi.amap.com/v3/ip?parameters', [
			'key' => 'b5cd86ae7b8a0819efa9490b08e16942',
			'ip' => $request->ip(),
		]);
		$ret = json_decode($ret);
		if (empty($ret->province)) {
			$ret = 0; //海外
		} else {
			$ret = 1; //国内
		}
		writeJson(1, '', $ret);
	}
	
	/**
	 * 校验$value是否非空
	 *  if not set ,return true;
	 *    if is null , return true;
	 **/
	protected function checkEmpty($value) {
		if (!isset($value))
			return true;
		if ($value === null)
			return true;
	
		
		return false;
	}
	
	/**
	 * 转换字符集编码
	 * @param $data
	 * @param $targetCharset
	 * @return string
	 */
	function characet($data, $targetCharset) {
		
		if (!empty($data)) {
			$fileType = $this->fileCharset;
			if (strcasecmp($fileType, $targetCharset) != 0) {
				$data = mb_convert_encoding($data, $targetCharset, $fileType);
			}
		}
		return $data;
	}
}
